<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <div class="hydrant-info-wrap">
          <el-form label-width="150px" :model="hydrantForm" :rules="hydrantFormRules" ref="hydrantForm" @submit.native.prevent>
              <el-form-item label="业主单位：" prop='organizationId'>
                  <el-select filterable v-model="hydrantForm.organizationId" @change="getFcfSelectList()">
                      <el-option
                          v-for="item in orgList"
                          :key="item.organizationId"
                          :label="item.shortName"
                          :value="item.organizationId">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="消火栓名称：" prop="name">
                  <el-input v-model="hydrantForm.name" auto-complete="off" placeholder="请输入名称"></el-input>
              </el-form-item>
              <el-form-item label="位置：" prop="location">
                  <el-input v-model="hydrantForm.location" auto-complete="off" placeholder="请输入位置"></el-input>
              </el-form-item>
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="经度：" prop="lon">
                          <el-input v-model="hydrantForm.lon" auto-complete="off" placeholder="请输入经度"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="纬度：" prop="lat">
                          <el-input v-model="hydrantForm.lat" auto-complete="lat" placeholder="请输入纬度"></el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-form-item label="选取经纬度：">
                  <div id="HyDrantInfoBaiduMap" style="width:100%;height:300px"></div>
                  <input id="unitName_mapInput" class="form-control" v-model="valtemp" placeholder="请输入地点"/>
              </el-form-item>
              <el-form-item label="可用状态：" prop="status">
                <el-radio v-model="hydrantForm.status" label="0">可用</el-radio>
                <el-radio v-model="hydrantForm.status" label="1">不可用</el-radio>
              </el-form-item>
              <el-form-item label="口径：" prop="carCount">
                  <el-input type="input" v-model="hydrantForm.caliber" auto-complete="off" placeholder="请输入口径"></el-input>
              </el-form-item>
              <el-form-item label="关联探测器：" prop="fcfsId">
                <el-select v-model="hydrantForm.fcfsId" id="defaultFcStructId"
                          placeholder="请选择关联探测器"
                          filterable
                          :filter-method="getFcfSelectList"
                          :loading="relateFcIdsSelectloading">
                  <el-option
                    v-for="item in relateFcOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                  <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page.sync="relateFcPageIndex"
                    small
                    layout="total, prev, pager, next"
                    :total="relateFcTotal">
                  </el-pagination>
                </el-select>
              </el-form-item>
              <el-form-item label="图片：" prop='pictures'>
                  <el-upload
                      :action="QINIUUPLOADURL"
                      :multiple="false"
                      ref="upload"
                      list-type="picture-card"
                      :data="qiniuData"
                      :on-success="handleAvatarSuccess"
                      :on-remove="handleRemovePic"
                      :on-error="handleError"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="$imgPreview"
                      :file-list="qiniuData.fileList"
                      :limit="1"
                      :on-exceed="handleExceed"
                      accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                      <i class="el-icon-plus"></i>
                  </el-upload>
              </el-form-item>
              <el-form-item label-width="0" class="verifyidentity-button">
                  <el-button @click.stop="closeFun" round>取消</el-button>
                  <el-button type="primary" @click="saveInfo('hydrantForm')" round>保存</el-button>
              </el-form-item>
          </el-form>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import BMap from 'BMap'
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import { getOrgList } from '@/api/org'
import { updateMunicipalHydrants,getFcfSelectList } from '@/api/sysConfig'
import { setTimeout } from 'timers'

var map
export default {
  name: 'importHydrantInfo',
  props: {
    oldInfo: {},
    closeFun: {
      type: Function,
      required: true,
    }
  },
  data () {
    return {
      valtemp: '',
      qiniuData: {//上传图片携带的参数
        token: '',
        key: '',
        fileList: []
      },
      orgList: [],
      hydrantForm: {
        id: 0,
        organizationId: '',
        name: '',
        location: '',
        lat: '',
        lon: '',
        status: "0",
        caliber: '',//口径
        fcfsId: '',//关联探测器
      },
      hydrantFormRules: {
        organizationId: [
          { required: true, message: '请选择业主单位', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      // 关联探测器
      relateFcIdsSelectloading: false,
      relateFcOptions: [],
      relateFcPageIndex: 1,
      relateFcTotal: 0
    }
  },
  created () {
    let that = this
    that.getToken()
    // 获取业主单位信息
    getOrgList({
      queryType: 0
    }).then(res => {
      if (res.status = 200) {
        if (!that.oldInfo.id) {
          that.hydrantForm.organizationId = res.data[0].organizationId
          that.getFcfSelectList()
        }
        that.orgList = res.data
      }
    })
    that.$nextTick(() => {
      // 是否有历史值
      if (that.oldInfo.id) {
        that.hydrantForm.id = that.oldInfo.id
        that.hydrantForm.organizationId = that.oldInfo.organizationId
        that.hydrantForm.name = that.oldInfo.name
        that.hydrantForm.location = that.oldInfo.location
        that.hydrantForm.lat = that.oldInfo.lat
        that.hydrantForm.lon = that.oldInfo.lon
        that.hydrantForm.status = String(that.oldInfo.status)
        that.hydrantForm.caliber = that.oldInfo.caliber
        if(that.oldInfo.fcfsId!=0)
        that.hydrantForm.fcfsId = that.oldInfo.fcfsId
        that.getFcfSelectList()
        // 设置上传图片初始值
        that.oldInfo.url ? $.each(that.oldInfo.url.split(','), (index, url) => {
          that.qiniuData.fileList.push({
            name: that.oldInfo.name + index,
            url: url
          })
        }) : ''
      }
      // 初始化地图
      that.initMap()
      /*
     * 解决带分页的下拉框回显值不在首页无法显示label问题
     */
      setTimeout(()=>{
        if(that.oldInfo.fcfName) {
          let $tags = $('#defaultFcStructId')
          let nameList = that.oldInfo.fcfName.split(',')
          for (let i=0, len=$tags.length; i < len; i++) {
            $tags[i].value = nameList[i]
          }
        }
      }, 100)
    })
  },
  methods: {
    // 获取关联探测器
    getFcfSelectList(name, pageChange) {
      let that = this
      // 重新搜索时页码复原   
      if(!pageChange) {
        this.relateFcPageIndex = 1
      }
      let parames = {
        fbsId: 0,
        organizationId: that.hydrantForm.organizationId,
        parentId: 0,
        pageIndex: this.relateFcPageIndex - 1,
        pageSize: 10,
        name: name || ''
      }
      that.relateFcIdsSelectloading = true
      getFcfSelectList(parames).then(res => {
        if(res.status === 200) {
          that.relateFcOptions = res.data
          that.relateFcTotal = res.total
        }
        that.relateFcIdsSelectloading = false
      })
    },
    // 地图初始化
    initMap () {
      let that = this
      var geoc = new BMap.Geocoder()
      //选取经纬度
      map = new BMap.Map("HyDrantInfoBaiduMap")
      map.enableScrollWheelZoom() // 允许缩放
      map.clearOverlays() // 先清除地图上的点
      map.enableKeyboard() // 启用键盘上下左右键移动地图
      map.setDefaultCursor("crosshair") // 设置鼠标样式

      //经纬度画线
      if(that.oldInfo.lon && that.oldInfo.lat){
        var new_point1 = new BMap.Point(that.oldInfo.lon, that.oldInfo.lat);
        var marker1 = new BMap.Marker(new_point1);  // 创建标注
        map.addOverlay(marker1);              // 将标注添加到地图中
        map.centerAndZoom(new_point1,16);
        //map.panTo(new_point1);
      }else{
        var position = new BMap.Point(116.331398,39.897445);
        map.centerAndZoom(position, 16);
      }

      map.addEventListener("click", function(e){
        // 通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
        var pt = e.point;
        geoc.getLocation(pt, function(rs){
          // addressComponents对象可以获取到详细的地址信息
          var addComp = rs.addressComponents;
          that.hydrantForm.location=addComp.province+","+addComp.city+","+addComp.district+","+addComp.street+","+addComp.streetNumber;
          // 打点
          map.clearOverlays() // 先清除地图上的点
          var marker = new BMap.Marker(pt);  // 创建标注
          map.addOverlay(marker);              // 将标注添加到地图中
          // 经纬度设置值
          that.hydrantForm.lon = pt.lng
          that.hydrantForm.lat = pt.lat
        })
      })
      setTimeout(() => {
        that.mapSearch()
      }, 1000)
    },
    // 搜索经纬度
    mapSearch () {
      var acSearch = new BMap.Autocomplete(
        {'input' : 'unitName_mapInput', 'location' : map}
      );
      acSearch.setInputValue(this.valtemp);
      acSearch.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        var local = new BMap.LocalSearch( map, { //智能搜索
            onSearchComplete: function(results) {
              var position=results.getPoi(0);//得到标注点坐标
              var lng = position.point.lng;
              var lat = position.point.lat;
              var gpsPoint = new BMap.Point(lng,lat);
              map.centerAndZoom(gpsPoint,16);
            }
        });
        local.search(myValue);
      });
    },
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload(file) {//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!");
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList;
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList;
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      });
    },
    handleExceed(files, fileList) {//文件超出个数限制时的钩子
      this.$message.warning(`只能上传一张图片！`);
    },
    handleCurrentChange(currentpage) {
      this.relateFcPageIndex = currentpage
      this.getFcfSelectList($('#defaultFcStructId .el-select__input').val(), true)
    },
    // 保存
    saveInfo(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this

      that.$refs[formName].validate((valid) => {
        if (valid) {
          if(that.hydrantForm.status=='0'){
            that.hydrantForm.status=0
          }else{
            that.hydrantForm.status=1
          }
          let parames = {
            id: that.hydrantForm.id,
            organizationId: that.hydrantForm.organizationId,
            name: that.hydrantForm.name,
            location: that.hydrantForm.location,
            lat: that.hydrantForm.lat,
            lon: that.hydrantForm.lon,
            status:that.hydrantForm.status,
            caliber: that.hydrantForm.caliber,//口径
            fcfsId: that.hydrantForm.fcfsId//关联探测器
          }
          parames.url = util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString()
          // 提交
          updateMunicipalHydrants(parames).then(res => {
            if(res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success'
              })
              that.closeFun(true)
            } else {
              that.$message({
                message: res.info,
                type: 'warning'
              })
            }
          })
        } else {
          return false
        }
      })
    },
  }
}
</script>
<style lang="scss">
.hydrant-info-wrap {
    #unitName_mapInput {
        position: absolute;
        left: 5%;
        top: 8px;
        padding: 0 10px;
        width: 50%;
        background-color: rgba(255, 255, 255, 0.8);
        height: 38px;
        color: #333;
        border: 0;
        border-top: 1px solid #eee;
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
        border-radius: 2px 0 0 2px;
        box-shadow: 1px 1.5px 1px rgba(0,0,0,.25);
    }
}
.tangram-suggestion-main {
    z-index: 9999999999;
}
</style>
